package tw.cating.karmasaver.rss;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.Html;

import tw.cating.karmasaver.rss.structer.rssNode;

public class rssHandler{
	String _RssTitle = null;
	ArrayList<rssNode> mList = new ArrayList<rssNode>();
	
	private static final String GOOGLE_READER_API = "http://www.google.com/reader/api/0/stream/contents/feed/";
	private static final int getCount = 20;
	
	public void parserUrl(rssSiteAdapter.rssSite site){
		String fullurl = GOOGLE_READER_API + site.url + "?n=" + getCount;
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet get = new HttpGet(fullurl);
		ResponseHandler<String> rh = new BasicResponseHandler();
		try {
			parseJSON(httpClient.execute(get, rh));
			site.title = _RssTitle;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected void parseJSON(String jsonStr) {
		try {
			JSONObject rssRoot = new JSONObject(jsonStr);
			if (rssRoot.has("title")) {
				_RssTitle = Html.fromHtml(rssRoot.getString("title")).toString();
			} else {
				_RssTitle = ""; 
			}
			
			if (rssRoot.has("items")) {
				JSONArray items = rssRoot.getJSONArray("items");
				for (int i = 0 ; i < items.length(); i++) {
					JSONObject rssItem = items.getJSONObject(i);
					rssNode node = new rssNode();
					node.setFrom(_RssTitle);

					if (rssItem.has("alternate")) {
						JSONArray array = rssItem.getJSONArray("alternate");
						if (array.length() > 0) {
							JSONObject alternate = array.getJSONObject(0);
							
							if (alternate.has("href"))
								node.setUrl(alternate.getString("href"));
							else
								continue;
						}
					}
					
					if (rssItem.has("title")) {
						node.setDescription(Html.fromHtml(rssItem.getString("title")).toString());
					} else
						continue;
					
					mList.add(node);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void reset() {
		mList.clear();
	}
	
	public int getCount() {
		// TODO Auto-generated method stub
		return mList == null ? 0 : mList.size();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		if (position >= mList.size() || position < 0)
			return null;
		
		return mList == null ? null : mList.get(position);
	}
}
